package com.example.blog.interceptor;

import com.example.blog.common.AppVariable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *  实现一个普通的
 *  登录拦截器
 */
@Component
public class LoginInterceptorSession implements HandlerInterceptor {
    /**
     * 返回 true -> 用户已登录.
     * 返回 false -> 用户未登录.
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 拿到 session 对象, 判断用户是否登录
        HttpSession session = request.getSession(false);
        // 判断用户是否登录
        if (session != null && session.getAttribute(AppVariable.USER_SESSION_KEY) != null) {
            // 用户已登录
            return true;
        }
        // 用户未登录, 重定向到登陆页面.
        response.sendRedirect("/login.html");
        return false;
    }
}
